<template>
  <me-table ref="table" :data="state.list" :pagination="pagination" @current-change="pageSizeChange" :handle="{
    delete: del
  }" :currentChange="currentRowChange">
    <template #head-handle>
      <el-button type="primary" @click="open">设置首页展示</el-button>
    </template>
    <!-- <el-table-column prop="avatar" label="头像" width="180" /> -->
    <el-table-column prop="user" label="商家">
      <template #default="{ row }">
        <span>{{ row.user.nickname }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="category" label="分类">
      <template #default="{ row }">
        <span>{{ row.category.name }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="title" label="标题" width="180" />
    <el-table-column prop="price" label="主图" width="300">
      <template #default="{ row }">
        <div>
          <el-image class="img" v-for="item in row.pictures" :key="item.url" :src="item.url"></el-image>
        </div>
      </template>
    </el-table-column>
    <!-- <el-table-column prop="description" label="描述" /> -->
    <el-table-column prop="price" label="价格">
      <template #default="{ row }">
        <div>
          {{ row.price }}
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="show" label="开启首页展示">
      <template #default="{ row }">
        <el-tag :type="row.show ? 'success' : 'info'">{{row.show ? '开启' : '未开启'}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="sort" label="首页展示顺序" />
    <el-table-column prop="state" label="状态" :filters="filters.slice(0, filters.length / 2)"
      :filter-method="filterState">
      <template #default="{ row }">
        <el-tag>{{ goodsState[row.state] }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="duration" label="有效天数" />
    <el-table-column prop="createTime" label="创建时间" />
  </me-table>
  <me-dialog v-model="dialogVisible" @confirm="submit(ruleFormRef)">
    <el-form ref="ruleFormRef" :model="state.formData" :rules="rules">
      <el-form-item label="是否展示" prop="show">
        <el-switch v-model="state.formData.show" />
      </el-form-item>
      <el-form-item label="展示顺序" prop="sort">
        <el-input v-model="state.formData.sort" />
      </el-form-item>
    </el-form>
  </me-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { getGoodsList, delGoods, editGoods } from '@/axios/api/goods'
import { goodsState } from '@/enum'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const filters: object[] = reactive([])
for (let key in goodsState) {
  console.log(key)
  filters.push({
    text: goodsState[key],
    value: key
  })
}

type Form = {show: boolean, sort: number, id: string}
const state = reactive({
  list: <object[]>[],
  formData: <Form>{}
})

const ruleFormRef = ref<FormInstance>()
const validateSort = (rule: any, value: any, callback: any) => {
  if (state.formData.show && !value) {
    // 开启展示，不设置顺序值提示错误
    callback(new Error('开启展示必须设置展示顺序！'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  imageUrl: [{ required: true, message: '请上传图片！', trigger: 'blur' }],
  sort: [
    { validator: validateSort , trigger: 'blur' }
  ]
})

const pagination = reactive({
  total: 0,
  index: 1,
  size: 20
})
const getList = () => {
  getGoodsList(pagination.index, pagination.size).then((res: any) => {
    state.list = res.records
    pagination.total = res.total
  })
}
onMounted(() => {
  getList()
})

const pageSizeChange = (index: number) => {
  pagination.index = index
  getList()
}

const filterState = (value: string, row: any) => {
  console.log(row, value)
  return row.state === Number(value)
}
const del = (id: string) => {
  delGoods(id).then(() => {
    getList()
  })
}

const dialogVisible= ref<boolean>(false)

const open = () => {
  if (!state.formData.id) return ElMessage({
    message: '请选择需要修改哪一行的数据',
    type: 'warning',
  })
  console.log(state.formData)
  dialogVisible.value = true
}
const currentRowChange = (row: any) => {
  const { show, sort, _id: id } = row
  state.formData = { show, sort, id }
  console.log(row)
}

const submit = (formEl: FormInstance | undefined) => {
  formEl?.validate(async valid => {
      if (valid) {
        await editGoods(state.formData)
        dialogVisible.value = false
        state.formData = <Form>{}
        getList()
        // state.list.unshift(res)
      }
    })
}
</script>

<style scoped>
</style>